package cn.com.dcsgo.controller;

import cn.com.dcsgo.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.io.Serializable;

/**
 * GlobalExceptionController
 *
 * @author Dcsgo
 * @since 2025/4/3 11:04
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionController {
    @ExceptionHandler(Throwable.class)
    public ResponseResult<Serializable> handleThrowable(Throwable t) {
        log.error(t.getMessage());
        return ResponseResult.fail(t.getMessage());
    }


    /**
     * 参数效验异常处理
     * 参考文章：https://blog.csdn.net/m0_69632475/article/details/136531252
     *
     * @param ex ex
     * @return 异常信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<Serializable> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder("前端参数校验失败!");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append(", ");
        }
        String msg = sb.toString();
        log.error(msg);
        return ResponseResult.fail(msg);
    }

    /**
     * 参数效验异常处理
     *
     * @param ex ex
     * @return 异常信息
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseResult<Serializable> handleConstraintViolationException(ConstraintViolationException ex) {
        log.error(ex.getMessage());
        return ResponseResult.fail(ex.getMessage());
    }
}
